package com.eliansun.service.mongo;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author liujin
 * @description mongo
 * @create 2019/7/3
 */

@Scope("prototype")
@Component
public class BaseDao {

    @Value("${system.mongo.dbname}")
    private String databaseName;

    @Value("${system.mongo.collectionName}")
    private String collectionName;

    @Value("${system.mongo.host}")
    private String host;

    private MongoClient mongoClient;

    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }

    public MongoClient getClient() {
        if (mongoClient == null) {
            mongoClient = new MongoClient(host);
        }
        return mongoClient;
    }

    public MongoDatabase getDB(){
        MongoDatabase mongoDatabase = getClient().getDatabase(databaseName);
        return mongoDatabase;
    }

    public MongoCollection<Document> getConnection() {
        if (getDB().getCollection(collectionName) != null) {
            return getDB().getCollection(collectionName);
        } else {
            this.getDB().createCollection(collectionName);
            return getDB().getCollection(collectionName);
        }
    }

    public void closeClient() {
        getClient().close();
        mongoClient = null;
    }
}